package com.application.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.model.Global;
import com.jfinal.ext.util.WxQrCode;
import com.jfinal.ext.util.qrcode.BgImage;
import com.jfinal.ext.util.qrcode.QRCodeUtil;
import com.jfinal.kit.PropKit;
import com.nmtx.doc.utils.HttpUtils;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.tools.ToolCache;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller("/api/qrcode")
public class QrcodeApiController extends BaseController {

    static final String proj = PropKit.get("proj_url");
    static final String path = PropKit.get("qrcode.dir", "d:/qrcode/");
    static final String h5Url = PropKit.get("h5_url");

    static long bgImgTime = 0;
    /**
     * 根据用户id动态生成二维码图片
     */
    public void index() {
        String id = getCUserIds();
        String url = proj + "/files/qrcode/qr_" + id + ".jpg";
        String text = h5Url + "?uid=" + id;
        String destPath = path + "qr_" + id + ".jpg";
        String imgPath = path + "ic_launcher.png";
        String bgPath = path + "ic_bg.jpg";

        File bgImg = new File(bgPath);
        File file = new File(destPath);
        if (!file.exists() || bgImg.lastModified() != bgImgTime) {
            try {
                Global g1 = Global.cacheGetByCode(Global.Code.qrcode_xy);
                Global g2 = Global.cacheGetByCode(Global.Code.qrcode_size);
                String[] xy = g1.getValue().split(",");
                String[] size = g2.getValue().split(",");
//                190, 550, 141, 141
                BgImage bg = new BgImage(bgPath, Integer.parseInt(xy[0]), Integer.parseInt(xy[1]), Integer.parseInt(size[0]), Integer.parseInt(size[1]));
                QRCodeUtil.encode(text, imgPath, destPath, true, bg);
                bgImgTime  = bgImg.lastModified();
            } catch (Exception e) {
                e.printStackTrace();
                error(500, "请求失败");
            }
        }

        success(url + "?t=" + file.lastModified());
    }


    public void wx() {
        try {
            String id = getCUserIds();
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", id);
            paramJson.put("page", "pages/public/register");
            paramJson.put("width", 430);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            String fileName = id + ".png";
            String uploadPath = proj + "/files/qrcode/xcx/" + fileName;
            String savePath = path + "xcx/" + fileName;

            if(!new File(savePath).exists()) {
               WxQrCode.getminiqrQr(getAccessToken(), savePath, paramJson);
                System.out.println("uploadPath: " + uploadPath);
                System.out.println("savePath: " + savePath);
            }
            success(uploadPath);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        error(500, "生成失败");
    }


    public String getAccessToken() {
        String access_token = ToolCache.get("access_token");
        try {
            //缓存时长
            if (StringUtils.isBlank(access_token)) {
                Map<String, String> params = new HashMap<String, String>();
                params.put("grant_type", "client_credential");
                params.put("appid", PropKit.get("xcx.appid"));
                params.put("secret", PropKit.get("xcx.secret"));
                String respData = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params, 500);
                System.out.println("getaccess_token=====\n" + respData);
                JSONObject json = JSON.parseObject(respData);
                access_token = json.getString("access_token");
                ToolCache.set("accesstoken", 60 * 60, access_token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return access_token;
    }


}
